package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.CaptchaUtil;
import com.example.lotterysystem.common.utils.RedisUtil;
import com.example.lotterysystem.common.utils.RegexUtil;
import com.example.lotterysystem.common.utils.SMSUtil;
import com.example.lotterysystem.service.VerificationCodeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeeService {
    //对于redis里面的key需要标准化，为了区分业务，应该给key定义前缀；
    private static final String VERIFICATION_CODE_PREFIX="verification_code_";
    //定义过期时间
    private static final Long VERIFICATION_CODE_EXPIRE_TIME=60L;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发送验证码
     * @param phoneNumber
     */
    @Override
    public void sendVerificationCode(String phoneNumber) {
        //效验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_FORMAT_ERROR);
        }
        //生成随机验证码
        String code= CaptchaUtil.generateCaptcha(4);
        //发送验证码
        SMSUtil.sendSMS(phoneNumber,code,"1");
        //将验证码存入redis
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_EXPIRE_TIME);
    }


    /**
     * 验证验证码
     * @param phoneNumber
     */
    @Override
    public String getVerificationCode(String phoneNumber) {
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_FORMAT_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }


}
